//
//  PostPictureVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/9/20.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "PostPictureVC.h"
#import "TopBackView.h"
#import "QiniuSDK.h"
#import "Common.h"
#import "WKProgressHUD.h"
#import "RootViewController.h"



@interface PostPictureVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong) UIButton *button1;
@property (nonatomic,strong) UIButton *button2;

@property (nonatomic) NSInteger integer;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) NSMutableArray *postArr;
@property (nonatomic,strong) WKProgressHUD *hud;
@property (nonatomic,copy) NSString *token;

@property (nonatomic,strong) NSMutableDictionary * dicUrl; //定位信息
//@property (nonatomic, strong) BMKGeoCodeSearch *geoCode;        // 地理编码
//@property (nonatomic, assign) CGFloat longitude;  // 经度
//@property (nonatomic, assign) CGFloat latitude; // 纬度



@end

@implementation PostPictureVC

- (void)viewDidLoad {
    [super viewDidLoad];
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"上传单据照片"];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.postArr = [NSMutableArray array];
    _dicUrl = [[NSMutableDictionary alloc]init];
    
    [self initTopView];
    
}

-(void)initTopView
{

    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64)];
    [self.view addSubview:self.scrollView];
    self.scrollView.contentSize = CGSizeMake(screenWidth, screenHeight + 1);
    self.scrollView.backgroundColor = GrayColor;
    
    
    UIView *firstV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, cellHeight)];
    firstV.backgroundColor = WhiteColor;
    [self.scrollView addSubview:firstV];
    

    UILabel *orderL = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 100 * kWidth, cellHeight)];
    orderL.text = @"单据照片";
    orderL.textColor = littleBlackColor;
    orderL.font = Font(14);
    [firstV addSubview:orderL];
    
   
    
    [self initButton];
    
}

-(void)initButton
{
    
    UIView *secondV = [[UIView alloc]initWithFrame:CGRectMake(0, cellHeight + 5* kHeight, screenWidth, 330 * kHeight)];
    secondV.backgroundColor = WhiteColor;
    [self.scrollView addSubview:secondV];
    
    
    UIImageView *imageV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"noPicture"]];
    imageV.frame = CGRectMake((screenWidth - 40)/2.0, 35 * kHeight, 40, 35);
    [secondV addSubview:imageV];
    
    UILabel *firstL = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(imageV.frame) , screenWidth, 40 * kHeight)];
    firstL.text = @"您还没有提交单据照片";
    firstL.textColor = carScrollColor;
    firstL.font = Font(20);
    firstL.textAlignment = NSTextAlignmentCenter;
    [secondV addSubview:firstL];
    
    UILabel *secondL = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(firstL.frame) , screenWidth, 20 * kHeight)];
    secondL.text = @"请到光线良好的地方拍照或者选择清晰的照片";
    secondL.font = Font(14);
    [secondV addSubview:secondL];
    secondL.textColor = carScrollColor;
    secondL.textAlignment = NSTextAlignmentCenter;
    
    
    //交接单照片
    self.button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    UIView *jiaojieV = [self backViewWithButton:self.button1 andString:@"DMS回执单" andFloat:18];
    
    [secondV addSubview:jiaojieV];
    
    //车辆照片
    self.button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    
    UIView *carV = [self backViewWithButton:self.button2 andString:@"客户运单第3联(蓝联)" andFloat:screenWidth - 18 - 128 * kWidth];
    
    [secondV addSubview:carV];
    
    
    UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmButton.frame = CGRectMake(18, CGRectGetMaxY(secondV.frame) + 20, screenWidth - 36, Button_height);
    [confirmButton setTitle:@"确认交车" forState:UIControlStateNormal];
    [confirmButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [confirmButton setBackgroundColor:YellowColor];
    [confirmButton addTarget:self action:@selector(confirmButton:) forControlEvents:UIControlEventTouchUpInside];
    confirmButton.layer.cornerRadius = 5;
    
    [self.scrollView addSubview:confirmButton];
    
    self.scrollView.contentSize = CGSizeMake(screenWidth, CGRectGetMaxY(confirmButton.frame) + 20);

    
}

/*
-(void)startLocation{
    
    _mapManager = [[BMKMapManager alloc]init];
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];

}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
//    NSLog(@"当前位置信息：didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    self.longitude = userLocation.location.coordinate.longitude;
    self.latitude = userLocation.location.coordinate.latitude;
    NSString * latitude = [NSString stringWithFormat:@"%f",self.latitude];
    NSString * longitude = [NSString stringWithFormat:@"%f",self.longitude];
    
    [_dicUrl setObject:latitude forKey:@"latitude"];
    [_dicUrl setObject:longitude forKey:@"longitude"];
    
    [self outputAdd];
    // 当前位置信息：didUpdateUserLocation lat 23.001819,long 113.341650
}
#pragma mark geoCode的Get方法，实现延时加载
- (BMKGeoCodeSearch *)geoCode
{
    if (!_geoCode)
    {
        _geoCode = [[BMKGeoCodeSearch alloc] init];
        _geoCode.delegate = self;
    }
    return _geoCode;
}
//#pragma mark 获取地理位置按钮事件
- (void)outputAdd
{
    // 初始化反地址编码选项（数据模型）
    BMKReverseGeoCodeOption *option = [[BMKReverseGeoCodeOption alloc] init];
    // 将数据传到反地址编码模型
    option.reverseGeoPoint = CLLocationCoordinate2DMake(self.latitude, self.longitude);
//    NSLog(@"%f - %f", option.reverseGeoPoint.latitude, option.reverseGeoPoint.longitude);
    // 调用反地址编码方法，让其在代理方法中输出
    [self.geoCode reverseGeoCode:option];
}

#pragma mark 代理方法返回反地理编码结果
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (result) {
        //        self.address.text = [NSString stringWithFormat:@"%@", result.address];
//        NSLog(@"位置结果是：%@ - %@", result.address, result.addressDetail.city);
        
        NSString * province = [NSString stringWithFormat:@"%@",result.addressDetail.province];
        NSString * city = [NSString stringWithFormat:@"%@",result.addressDetail.city];
        //区县名称
        NSString * district = [NSString stringWithFormat:@"%@",result.addressDetail.district];
        NSString * address = [NSString stringWithFormat:@"%@",result.address];
        
        [_dicUrl setObject:province forKey:@"province"];
        [_dicUrl setObject:city forKey:@"city"];
        [_dicUrl setObject:district forKey:@"county"];
        [_dicUrl setObject:address forKey:@"address"];
        // 定位一次成功后就关闭定位
        [_locService stopUserLocationService];
        
//        [Common afPostRequestWithUrlString:trail_Url parms:_dicUrl finishedBlock:^(id responseObj) {
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
//            NSLog(@"%@",dic[@"message"]);
//            NSString * userStatus = [NSString stringWithFormat:@"%@",dic[@"success"]];
//            if ([userStatus isEqualToString:@"1"]) {
//                NSLog(@"司机提交照片GPS成功");
//            }else{
//                NSLog(@"司机提交照片GPS失败");
//            }
//        } failedBlock:^(NSString *errorMsg) {
//        }];

        
    }else{
        NSLog(@"%@", @"找不到相对应的位置");
    }
    
}
 */

#pragma mark 提交
-(void)confirmButton:(UIButton *)sender
{
    
    if (self.postArr.count != 2) {
        
        [WKProgressHUD popMessage:@"请将信息补充完整" inView:self.view duration:1.5 animated:YES];
        
        
    } else {
        
        self.hud  = [WKProgressHUD showInView:self.view withText:@"" animated:YES];

        
        NSData * jsonData = [NSJSONSerialization dataWithJSONObject:self.postArr options:NSJSONWritingPrettyPrinted error:nil];
        NSString * jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        Common *c = [[Common alloc]init];
        
        NSDictionary *dictionary = @{@"id":self.orderId,@"attachs":jsonString};
        [_dicUrl setObject:self.orderId forKey:@"id"];
        [_dicUrl setObject:jsonString forKey:@"attachs"];
        NSString *string ;
      
        string = stan_waybill_delivery;

//        [self startLocation];
        NSLog(@"%@",_dicUrl);
        
        [c afPostRequestWithUrlString:string parms:_dicUrl finishedBlock:^(id responseObj) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            
            [self.hud dismiss:YES];
            
            [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
            
            if ([dic[@"success"] boolValue]){
                

                //延迟执行
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self backAction];
                    
                });
                
            }
        
            
        } failedBlock:^(NSString *errorMsg) {

            [self.hud dismiss:YES];

        }];
        
        
        
    }
}




-(UIView *)backViewWithButton:(UIButton *)button andString:(NSString *)string andFloat:(CGFloat)x
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(x, 150 * kHeight, 128 * kWidth, 148 * kHeight)];
    
    button.frame = CGRectMake(0, 0, 128 * kWidth, 128 * kWidth);
    [button setBackgroundImage:[UIImage imageNamed:@"car_add"] forState:UIControlStateNormal];
    [view addSubview:button];
    [button addTarget: self action:@selector(getPicture:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMidX(button.frame) - 75 * kWidth, CGRectGetMaxY(button.frame) + 10, 150 * kHeight, 20 * kWidth)];
    label.text = string;
    label.font = Font(13);
    label.textColor = carScrollColor;
    label.textAlignment = NSTextAlignmentCenter;
    
    [view addSubview:label];
    return view;
}

-(void)getPicture:(UIButton *)sender
{
    if (sender == self.button1) {
        _integer = 1;
    } else {
        _integer = 2;
    }
    
    [self tapSelectPicture];
    
}

//获取图片
-(void)tapSelectPicture
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf getPictureFromCamera];
        
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf getPictureFromLibrary];
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark 拍照
-(void)getPictureFromCamera
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark 从相册选取
-(void)getPictureFromLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}


#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        if (_integer == 1) {
            [self.button1 setImage:image forState:UIControlStateNormal];
        } else {
            [self.button2 setImage:image forState:UIControlStateNormal];
        }
        
        self.hud  = [WKProgressHUD showInView:self.view withText:@"" animated:YES];
        
        
        //        NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
        //        MineCell *cell = [self.tableView cellForRowAtIndexPath:index];
        //
        //        cell.ImageView.image = image;
        
        //上传服务器
        [self getTokenFromQN];
        
    }];
}


-(NSData *)getImageWith:(UIImage *)image
{
    NSData *data = nil;
    if (UIImagePNGRepresentation(image)) {
        
        data = UIImageJPEGRepresentation(image, 0.3);
        
        
    } else {
        data = UIImagePNGRepresentation(image);
        
        
    }
    
    return data;
}

#pragma mark 从七牛获取Token
-(void)getTokenFromQN
{
    
    [Common requestWithUrlString:picture_qiniu_token contentType:application_json finished:^(id responseObj) {
        if ([responseObj[@"success"] boolValue]) {
            
            
            self.token = responseObj[@"data"];
            //
            //            NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
            //            MineCell *cell = [self.tableView cellForRowAtIndexPath:index];
            //if
            if (_integer == 1) {
                [self uploadImageToQNWithData:[self getImageWith:self.button1.imageView.image]];
                
            } else {
                [self uploadImageToQNWithData:[self getImageWith:self.button2.imageView.image]];
                
            }
            
        }
    } failed:^(NSString *errorMsg) {
        
        [self.hud dismiss:YES];
        
        NSLog(@"%@",errorMsg);
    }];
    
    
    
}

-(void)uploadImageToQNWithData:(NSData *)data
{
    
    QNUploadManager *upManager = [[QNUploadManager alloc]init];
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:data key:nil token:self.token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        //        [self changePhotoWithString:resp[@"key"]];
        //提车type1010  交车3010
        NSDictionary *dic ;
        
//        if ([self.titleString isEqualToString:@"提车照片"]) {
//            
//            
//            if (_integer == 1) {
//                dic = @{@"image":resp[@"key"],
//                        @"type":@"1010"};
//            } else {
//                dic = @{@"type":@"1020",
//                        @"image":resp[@"key"]};
//            }
//        } else {
        
            if (_integer == 1) {
                dic = @{@"image":resp[@"key"],
                        @"type":@"3010"};
            } else {
                dic = @{@"type":@"3020",
                        @"image":resp[@"key"]};
            }

//        }
        
        
        
        
        if (self.postArr.count > 0) {
            
            for (int i = 0 ;i < self.postArr.count; i++) {
                
                if ([self.postArr[i][@"type"] isEqualToString:dic[@"type"]]) {
                    
                    [self.postArr removeObjectAtIndex:i];
                }
            }
            
            [self.postArr addObject:dic];
            
        } else {
            [self.postArr addObject:dic];
            
        }
        
        [self.hud dismiss:YES];
        
        
    } option:uploadOption];
}
-(void)viewWillAppear:(BOOL)animated
{
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
}



-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
